package src.com.neusoft.nep.common;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileUtils2 {
    public static Map readMapObject(String fileName){
        File file = new File(fileName);
        Map map = null;
        try {
            if (file.length() == 0) {
                map = new HashMap<>();
            } else {
                FileInputStream fis = null;
                fis = new FileInputStream(file);
                ObjectInputStream ois = new ObjectInputStream(fis);
                map = (Map) ois.readObject();
            }
        }catch (FileNotFoundException e){
            throw new RuntimeException(e);
        }catch (ClassNotFoundException e){
            throw new RuntimeException(e);
        }catch (IOException e){
            throw new RuntimeException(e);
        }
        return map;
    }
    public static void writeMapObject(String fileName, Map map){
        try {
            File file = new File(fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(map);
            oos.flush();
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }
    // 读取List<Map<String, String>>格式的数据
    public static List<Map<String, String>> readListMapObject(String fileName) {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName))) {
            return (List<Map<String, String>>) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            // 文件不存在或格式错误时返回空列表
            return new ArrayList<>();
        }
    }

    // 写入List<Map<String, String>>格式的数据
    public static void writeListMapObject(String fileName, List<Map<String, String>> dataList) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName))) {
            oos.writeObject(dataList);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("保存数据失败", e);
        }
    }
}